<template>
    <view class="video-list-page">
        <!-- 自定义navbar -->
        <view class="nav-bar">
            <BackNav title="搜索课程" bgColor="#fff" :show-back="true" />
        </view>

        <!-- 搜索栏 -->
        <view class="search-bar">
            <Searcher :keyword="searchKeyword" @update:keyword="searchKeyword = $event" @search="onSearch" auto-focus />
        </view>

        <u-tabs style="width: 300rpx; margin: 0;background-color: #fcfcfc;" :list="[{ name: '收藏量' }, { name: '播放量' }]" :is-scroll="false"
            :current="currentTab" @change="changeTab"></u-tabs>
        <!-- 视频列表 - 两列显示 -->
        <scroll-view style="height: calc(100vh - 200rpx);flex: 1;" scroll-y @scrolltolower="loadMore">
            <!-- 空态 -->
            <view v-if="isEmpty" class="no-more">暂无数据...</view>

            <!-- 双列瀑布流 -->
            <view v-else class="video-list">
                <view v-for="(item, index) in videoList" :key="index" class="video-item">
                    <view class="video-card" @click="goToVideoDetail(item)">
                        <!-- 封面 -->
                        <image class="cover" :src="item.coverUrl" mode="aspectFill" />
                        <!-- 信息区 -->
                        <view class="info">
                            <view class="course-name">
                                <u-tag type="primary" mode="dark" :text="item.subjectName" size="small"
                                    shape="square" />
                                <u-text :size="27" style="width: 220rpx;" lines="1">{{ item.videoTitle }}</u-text>
                            </view>
                            <!-- <view class="video-name text-ellipsis">{{ item.subjectName }}</view> -->
                            <view class="school-name text-ellipsis">{{ item.schoolName }}</view>
                            <view class="school-name text-ellipsis">{{ item.gradeName }}&nbsp;&nbsp;{{
                                item.createdTime.substring(0, 10) }}</view>
                        </view>
                    </view>
                </view>
            </view>
            <!-- 底部状态 -->
            <view v-if="loading" class="loading-more">加载中...</view>
        </scroll-view>
        <!-- 加载更多 -->
    </view>
</template>

<script setup lang="ts">
import { onLoad } from '@dcloudio/uni-app'
import { ref } from 'vue'
import uniReq from '@/api/uniReq'
import BackNav from '@/components/backNav/backNav.vue'
import Searcher from '@/components/searcher/searcher.vue'


const currentPage = ref(1)
const pageSize = ref(50)
const loading = ref(false)
const hasMore = ref(true)
const totalPages = ref(0)

// 搜索关键词
const searchKeyword = ref('')
const selectedCategory = ref('')
const selectorPlaceholder = ref('科目')
const onCategoryChange = (e: any) => {
    selectedCategory.value = e.item.value
    selectorPlaceholder.value = e.item.label
    // 执行分类筛选逻辑
    getVideoList(selectedCategory.value)
}
const onSearch = () => {
    console.log(searchKeyword.value);
    getVideoList()
}


// 分类列表
const categoryList = ref([])

const getSubjectList = async () => {
    try {
        const res: any = await uniReq({
            url: '/subject/select-subject-nam-and-id',
            method: 'GET',
            // data: {}
        })
        if (res.status === 200) {
            categoryList.value = res.data.map(item => ({
                value: item.subjectId,
                label: item.name
            }))
        } else {
            uni.showToast({
                title: res.message || '获取学科列表失败',
                icon: 'none'
            })
        }
    } catch (error) {
        console.error('获取学科列表失败:', error)
        uni.showToast({
            title: '网络错误，请稍后重试',
            icon: 'none'
        })
    }
}

const currentTab = ref(0)
const changeTab = (index: number) => {
    currentTab.value = index
    console.log('切换到标签页:', tabs[index].title)
    getVideoList()
}



onLoad(async (options) => {
    console.log('onLoad options:', options)
    selectorPlaceholder.value = options.name;//最弱智的写法，直接使用placeholder回显值字段。太折磨人了其他地方也需要修改。
    selectedCategory.value = options.gradeId
    await getSubjectList()
    getVideoList(options.id, options.gradeId)

})

// 视频列表数据
const videoList = ref([])
const getVideoList = async (subjectId?: string, gradeId?: string) => {
    try {
        loading.value = true

        const params = {
            pageIndex: currentPage.value,
            pageSize: pageSize.value,
            filter: {
                subjectId: subjectId,
                gradeId: gradeId,
                keyWords: searchKeyword.value
            }

        }

        const res: any = await uniReq({
            url: '/video-content/selectPage',
            method: 'POST',
            data: params
        })

        if (res.status === 200) {
            const { list, total: totalCount } = res.data
            videoList.value = [...videoList.value, ...list]
            hasMore.value = list.length >= pageSize.value
            totalPages.value = Math.ceil(totalCount / pageSize.value)
        } else {
            uni.showToast({
                title: res.message || '获取视频列表失败',
                icon: 'none'
            })
        }
    } catch (error) {
        console.error('获取视频列表失败:', error)
        uni.showToast({
            title: '网络错误，请稍后重试',
            icon: 'none'
        })
    } finally {
        loading.value = false
    }
}

// 跳转到视频详情
const goToVideoDetail = (item: any) => {
    uni.navigateTo({
        url: `/pages/videoDetail/videoDetail?data=${encodeURIComponent(JSON.stringify(item))}`
    })
}

//加载更多
const loadMore = () => {
    console.log('加载更多', currentPage.value);
    loading.value = true;
    currentPage.value++;
    getVideoList()
}

// 格式化时长
const formatDuration = (seconds: number) => {
    const hours = Math.floor(seconds / 3600)
    const minutes = Math.floor((seconds % 3600) / 60)
    if (hours > 0) {
        return `${hours}:${minutes.toString().padStart(2, '0')}`
    }
    return `${minutes}分钟`
}

// 格式化观看数
const formatViews = (views: number) => {
    if (views >= 10000) {
        return `${(views / 10000).toFixed(1)}万`
    }
    return `${views}`
}
</script>

<style scoped lang="scss">
.nav-bar {
    height: 100rpx;
}

.video-list-page {
    padding: 20rpx;
    background: linear-gradient(to bottom, #fff 15%, #f5f5f5 30%); //渐变色;;
    height: 100vh;
}

.search-bar {
    display: flex;
    align-items: center;
    // margin-bottom: 20rpx;
    padding: 20rpx;
    background-color: white;
    border-radius: 10rpx;
}

.search-input {
    flex: 1;
    height: 60rpx;
    padding: 0 20rpx;
    border: 1px solid #ddd;
    border-radius: 30rpx;
    font-size: 28rpx;
}

.search-btn {
    margin-left: 20rpx;
    padding: 15rpx 30rpx;
    background-color: #007aff;
    color: white;
    border-radius: 30rpx;
    font-size: 28rpx;
}

/* 容器 */
.video-list {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    padding: 20rpx;
    gap: 20rpx;
    /* 列间距 */
}

/* 单列卡片 - 双列时宽度 48% */
.video-item {
    width: 48%;
}

/* 卡片本体 */
.video-card {
    background: #fff;
    border-radius: 12rpx;
    height: 350rpx;
    overflow: hidden;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.06);
    transition: transform 0.2s;

    &:active {
        transform: scale(0.98);
    }

    /* 封面 16:9 */
    .cover {
        width: 100%;
        height: 200rpx;
        /* 16:9 比例 */
        border-radius: 12rpx 12rpx 0 0;
    }

    /* 信息区 */
    .info {
        padding: 12rpx 16rpx 16rpx;

         .course-name {
            display: flex;
            align-items: center;
            flex-wrap: nowrap;
            font-size: 28rpx;
            color: #333;
            font-weight: 500;
        }

        .video-name {
            font-size: 26rpx;
            color: #666;
            margin-top: 6rpx;
        }

        .school-name {
            font-size: 24rpx;
            color: #999;
            margin-top: 4rpx;
        }
    }
}

/* 文字省略号 */
.text-ellipsis {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}

/* 空态 */
.no-more {
    text-align: center;
    padding: 60rpx 0;
    font-size: 28rpx;
    color: #999;
}

/* 加载更多 */
.loading-more {
    text-align: center;
    padding: 30rpx 0;
    font-size: 26rpx;
    color: #666;
}

:deep(.u-tag) {
    margin-right: 10rpx;
    padding-left: 5rpx;
    // width: 60rpx;
    height: 35rpx;
    line-height: 37rpx;
    font-size: 24rpx;
    text-align: center;
}
</style>